<template>
    <iframe style="display: none;" :src="baseUrl" frameborder="0"></iframe>
    <div class="main">
      <div class="payment-success-container">
        <div class="img">
            <img v-if="lang == 'zh'" width="120" src="../../assets/logoZ.png" alt="">
            <img v-if="lang == 'en'" width="120" src="../../assets/logoZ_en.png" alt="">
            
        </div>
  
        <div class="message">
          <h1 class="amount">{{ $t('Y_stored') }}</h1>
        </div>
        <div class="order-info">
          <h1>{{ $t('Y_amount') }} {{ amount || '0.00' }}</h1>
          <p><strong>{{ $t('order_number') }}</strong> <span>{{ order_num || '-' }}</span></p>
        </div>
        <div class="actions" v-if="!isPay_complete">
          <button @click="pay">{{ $t('Instant_stored') }}</button>
        </div>
        <div class="payCom"  v-if="isPay_complete">
          <button>{{ $t('Stored_successfully') }}</button>
        </div>
      </div>

      <div v-if="visible" class="modal-overlay" @click.self="closeModal">
        <div class="modal">
            <div class="modal-header">
              <h3>{{ $t('Verify_code') }}</h3>
              <div class="close" @click="handleClose"></div>
            </div>
            <div class="modal-body">
              <!-- <label for="password">支付密码</label> -->
              <input maxlength="6" type="password" v-model="password" id="password" :placeholder="$t('pwd_tip')">
            </div>
            <div class="modal-footer">
              <button @click="handleClose">{{ $t('cancellation') }}</button>
              <button @click="handleSubmit">{{ $t('confirm') }}</button>
            </div>
          </div>
        </div>  
      </div>

    <div v-if="lang == 'zh'">
      <div v-if="visible_setPwd" class="modal-setPwd" @click.self="closeModal">
        <div class="modal">
            <div class="modal-header">
              <h3>設置安全碼</h3>
              <p>安全碼用于支付時的安全保障，請您設置！</p>
              <p>注意：安全碼設置后無法修改</p>
              <div class="close" @click="handleClose_pwd"></div>
            </div>
            <div class="modal-body">
              <!-- <label for="password">支付密码</label> -->
              <input maxlength="6" type="password" v-model="set_password" id="password" placeholder="請輸入安全碼">
            </div>
            <div class="modal-footer">
              <button @click="handleClose_pwd">取消</button>
              <button @click="handleSubmit_setPWd">确认</button>
            </div>
        </div>
      </div> 
    </div> 
    <div v-if="lang == 'en'">
      <div v-if="visible_setPwd" class="modal-setPwd" @click.self="closeModal">
        <div class="modal">
            <div class="modal-header">
              <h3>Set security code</h3>
              <p>The security code is used for secure verification operations during platform payments. Please set it upv！</p>
              <p>Attention: After setting the security code, it cannot be modified</p>
              <div class="close" @click="handleClose_pwd"></div>
            </div>
            <div class="modal-body">
              <!-- <label for="password">支付密码</label> -->
              <input maxlength="6" type="password" v-model="set_password" id="password" placeholder="Please set 6 as the digital security code">
            </div>
            <div class="modal-footer">
              <button @click="handleClose_pwd">cancel</button>
              <button @click="handleSubmit_setPWd">confirm</button>
            </div>
        </div>
      </div> 
    </div> 

    <div v-if="lang == 'zh'">
      <Dialog :title="'餘額不足'" :title2="'您的Y幣不足，是否前往儲值？'" :cancel_title="'取消'" :sub_title="'確認'" :visible="dialog_show" :handleClose='dialog_hide' :paySubmit="toRecharge"/>
      <Dialog :title="'儲值Y幣是否完成？'" :cancel_title="'未完成'" :sub_title="'已完成'" :visible="dialog_show2" :handleClose='paySubmit' :paySubmit="paySubmit"/>
    </div>
    
    <div v-if="lang == 'en'">
      <Dialog :title="'Sorry, your credit is running low'" :title2="'Your Y coins are insufficient. Would you like to deposit some?'" :cancel_title="'cancel'" :sub_title="'confirm'" :visible="dialog_show" :handleClose='dialog_hide' :paySubmit="toRecharge"/>
      <Dialog :title="'Has the stored value of Y coins been completed？'" :cancel_title="'Not Completed'" :sub_title="'Completed'" :visible="dialog_show2" :handleClose='paySubmit' :paySubmit="paySubmit"/>
    </div>
  </template>
  
  <script setup>
  import { useRoute } from 'vue-router';
  import axios from '@/utils/api'
  import { ref,onMounted,reactive,watchEffect } from "vue";
  import { useUserInfoStore } from '@/store/modules/user_info/index';
  import Dialog from "@/components/Dialog/index.vue"
  import {generateJWT} from "@/utils/jwt"
  const user_infoStore = useUserInfoStore();
  let user_info = reactive(user_infoStore.userInfo)
  
  const route = useRoute();
  
  const user_id = route.query.user_id
  const amount = route.query.amount
  const game_id = route.query.game_id
  const order_num = route.query.order_num

  const password = ref('')
  const set_password = ref('')
  const visible = ref(false);
  const visible_setPwd = ref(false);

  let dialog_show = ref(false)
  const dialog_hide = () => {
      dialog_show.value = false
  }

  let dialog_show2 = ref(false)
  const dialog_hide2 = () => {
      dialog_show2.value = false
  }

  const paySubmit =async ()=>{
    await getUserInfo()
    dialog_hide2()
  }

  const getUserInfo = async () =>{
	    const data = {
	        user_id:user_info.id
	    }
	    const list = await axios.post('/getUserInfo',data)
	    Object.assign(user_info,list.data)
	    // console.log(userInfo,'userInfo');
	    user_infoStore.setUserinfo(list.data.user_info)
	}

  
  const handleClose = () => {
    visible.value = false
    password.value = ''
  };

  const handleClose_pwd = () => {
    visible_setPwd.value = false
    set_password.value = ''
  };

  const handleSubmit = () => {
    if (password.value) {
        getOrder()
    } else {
      if(lang.value == 'en'){
        ElMessage.error('Please fill in the security code');
      }else{
        ElMessage.error('請填寫安全碼');
      }
        
    }
  
  };

  const handleSubmit_setPWd = () => {
    if (set_password.value) {
      setPwd()
        
    } else {
      if(lang.value == 'en'){
        ElMessage.error('Please fill in the set security code');
      }else{
        ElMessage.error('請填寫設定的安全碼');
      }
        
    }
  
  };

  const isPay_complete = ref(false)
  const getOrder = async () =>{
      const data = await axios.get('/wallet_pay?order_num='+order_num+'&user_id='+user_id+'&amount='+amount+'&game_id='+game_id+'&wallet_password='+password.value)
      console.log(data);
      if(data.code == 200){
        handleClose();
        if(lang.value == 'en'){
          ElMessage.success('Pay Success');
        }else{
          ElMessage.success('儲值成功');
        }
        // fbq('track', 'Purchase',{value:amount,currency:'USD'}); 
        // console.log('支付完成-Purchase',fbq);
        isPay_complete.value = true
        setTimeout(() => {
          // window.parent.postMessage('getInfo', '*');
          window.parent.postMessage('unShow', '*');
          window.close()
        }, 2000);
      }else if(data.code == 9005){
        ElMessage.warning(data.message);
        visible.value = false
        password.value = ''
        visible_setPwd.value = true
      }else{
        ElMessage.error(data.message);
      }
      
  }

  const setPwd = async () =>{
      const info = {
        user_id: user_id,
        wallet_password: set_password.value
      }
      const data = await axios.post('/setWalletPassword',info)
      console.log(data);
      if(data.code == 200){
        handleClose_pwd();
        visible.value = true
        ElMessage.success(data.message);

        getUserInfo()
      }else{
        ElMessage.error(data.message);
      }
      
  }
  
  let pixel_code = ref('')
  const pay = ()=>{
    console.log(user_info.money,amount,user_info.money < amount);
    
    if(user_info.money < amount){
      dialog_show.value = true
      return
    }

    // 判断是否设置安全码，弹出设置安全码
    if(user_info.password == null || user_info.password == ''){
        visible_setPwd.value = true
        return
    }
    visible.value = true
    
  }

  const toRecharge = ()=>{
    dialog_hide()
    setTimeout(() => {
      dialog_show2.value = true
    }, 1500);
    console.log(window.parent.innerWidth,'window.parent.innerWidth');
    if(window.parent.innerWidth < 1024){
      window.open(`//${window.location.host}/h5/#/pages/Recharge/recharge_center/index`)
    }else{
      window.open(`//${window.location.host}/#/recharge`)
    }
    
  }
  onMounted(()=>{
    window.parent.postMessage('closeLoadding', '*');
  })
  // onMounted(() => {
  //   // 创建 script 元素
  //   const script = document.createElement('script');
  //   script.src = 'https://connect.facebook.net/en_US/fbevents.js';
  //   script.async = true;
    
  //   // 当脚本加载完成后初始化 Facebook Pixel
  //   script.onload = () => {
  //       // Facebook Pixel 初始化代码
  //       !function(f,b,e,v,n,t,s){
  //           console.log(f.fbq,'f.fbq');
  //           if(f.fbq) return;
  //           n = f.fbq = function(){n.callMethod ?
  //           n.callMethod.apply(n, arguments) : n.queue.push(arguments)};
  //           if(!f._fbq) f._fbq = n;
  //           n.push = n;
  //           n.loaded = !0;
  //           n.version = '2.0';
  //           n.queue = [];
  //           t = b.createElement(e);
  //           t.async = !0;
  //           t.src = v;
  //           s = b.getElementsByTagName(e)[0];
  //           s.parentNode.insertBefore(t, s);
  //       }(window, document, 'script', 'https://connect.facebook.net/en_US/fbevents.js');

  //       switch(game_id){
  //           case '33':
  //               pixel_code.value = '466861299315951';
  //               break;
  //           case '70205':
  //               pixel_code.value = '348457851535499';
  //               break;    
  //       }
  //       // Facebook Pixel 配置
  //       fbq('init', pixel_code.value, {
  //           autoConfig: true,
  //           disableThirdPartyCookies: true
  //       });
  //   };
  //   document.head.appendChild(script);
// });

  let lang = ref('')
  if(localStorage.getItem('lang') == 'en'){
      lang.value = 'en'
  }else{
      lang.value = 'zh'
  }

  watchEffect(() => {
    let value = set_password.value;
    let numericValue = value.replace(/\D/g, ''); // 移除非数字字符

    if (value !== numericValue) {
        set_password.value = numericValue; // 只更新如果有变化
    }

    let value2 = password.value;
    let numericValue2 = value2.replace(/\D/g, ''); // 移除非数字字符

    if (value2 !== numericValue2) {
      password.value = numericValue2; // 只更新如果有变化
    }
  });


  let baseUrl = ref('')

  const users = [
      'b1b19539394c7e8429115766fbf86c95',
      'd7c8978cd524bae34c5954c08e19a085',
      '860921f48bd935320ca8b81b99b45445',
      '7de837f08a4efe02eb795f0e2f7f2bb2',
      '2453b28e9bd74a9028a6db5143ee3434',
      '3c5019172edb78b938f92782fea5961b',
      'db774fbe9aabb48c11218efcd12abf2f',
      '6c146c4119715cc04cb97576cb7fd940',
      '029003a1faafb8bed8cc3fc7229cb65d',
      '9614f292323683d3852b39833529e0d4',
      '8ca0873c6de7cce29fc50c4454750da3',
      'a11bd5b86385c1346522ffba25aa410e',
      'b36a3d9216581d1a54e9897bcf95fdf7',
      'ac88cde2dd7ada4fea478895d7c39e2b',
      '980e6010b3da577c4a95d0277bfa5735',
      '72719a0b7ab3cd3e018efa088eb98efc',
      '32ef473cb27b4382453ebcc9d9827de7',
      '595bb439cc8b1e1a983188a07157195d',
      '594fb821941683929ba978550082ebf1',
      'd33d7ab32adefa2bc96b5643b00373a3',
      'a0ac0febd66c2cd9a1c86eb869b69470',
      'c7f8b5675f74f4122d7229937f666558',
      '35bd623ef2f4bafeff54cdd4d2f7f7cf',
      'e481fdf407ae02e634b6e38997db92fe',
      'e75c0b8b354f89ebc8303910160af53b',
      'a905b3bb43046dbc9c68855a72670d03',
      '67851339f29713dde76299ba3f53d6d4',
      '3340d01b1eab4c3eae12725b5b5537e4',
      'd1af8313122ecba25fafe2f90e6beb04',
      '7ed8274dc1be788a86ada4a50b4c6984',
      '2ccc90a24f9e2585cb39dc5cedd8be6d',
      '8db9e078854ef9ad1bd16f072aac173a',
      '304d9f340867acdb83acba3d6786ae63',
  ];
  const randomUser = users[Math.floor(Math.random() * users.length)];
  // console.log(randomUser);

  generateJWT('jwt_web', randomUser).then(result => {
      baseUrl.value = window.baseUrl+'/index.php/V1/'+result.token
      getUserInfo()
  });
  </script>
  
  <style lang="less" scoped>
  @media (min-width: 1024px) {
    .payment-success-container{
      width: 500px;
      /* border-radius: 15px; */
    }
  }
  .main{
    background-color: #eeeeee;
    height: 100vh;
  }
  .red{
    color: red !important;
  }
  .yellow{
    color: rgb(241, 176, 83) !important;
  }
  .payment-success-container {
    display: flex;
    flex-direction: column;
    height: 100vh;
    text-align: center;
    background-color: white;
    
  }
  .img{
    margin-top:80px;
  }
  .success-icon {
    font-size: 80px;
    color: #52c41a;
    margin-bottom: 20px;
  }
  
  .message h1 {
    font-size: 22px;
    /* color: rgb(37, 182, 6); */
    margin-bottom: 10px;
    margin-top: 5px;
    font-weight: 500;
  }
  .productName{
    font-size: 20px;
    color: #000000;
    margin-top: 50px;
  }
  .money {
    font-size: 32px;
    color: #000000;
    margin-top: 5px;
    font-weight: bold;
  }
  
  .order-info {
    margin-top: 50px;
    text-align: center;
    font-size: 13px;
    color: #333;
    width: 80%;
  }
  
  .order-info p {
    margin: 10px 0;
    margin-top: 50px;
    display: flex;
    justify-content: space-between;
  }
  .order-info span,.order-info strong{
    margin: 0;
  }
  .actions {
    margin-top: 80px;
  }
  
  .actions button {
    display: inline-block;
    padding: 7px 70px;
    margin: 10px;
    font-size: 16px;
    color: #1bafea;
    border: 1px solid #1bafea;;
    background-color: transparent;
    border-radius: 4px;
    cursor: pointer;
    transition: background-color 0.3s ease;
  }
  
  .actions button:hover {
    background-color: #1bafea;
    color: white;
  }


  /* 模态框样式 */
.modal-overlay,.modal-setPwd {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.7);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}
.modal-setPwd{
  z-index: 1001 !important;
}
.modal {
  background: linear-gradient(to bottom right, #f9f9f9, #ffffff);
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2);
  width: 320px;
  text-align: center;
  position: relative;
}

.modal-header {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 20px;
  flex-direction: column;
  p{
    font-size: 13px;
    margin-top: 5px;
    color: #7f7f7f;
  }
}

.modal-header h3 {
  margin: 0;
  font-size: 24px;
  color: #3c4043;
  font-family: 'Roboto', sans-serif;
}

.close-button {
  background: none;
  border: none;
  font-size: 28px;
  color: #9aa0a6;
  cursor: pointer;
  transition: color 0.3s ease;
  position: absolute;
  right: 20px;
  top: 10px;
}

.close-button:hover {
  color: #1a73e8;
}

.modal-body {
  margin-bottom: 20px;
}

.modal-body label {
  display: block;
  font-size: 16px;
  color: #3c4043;
  margin-bottom: 5px;
  font-family: 'Roboto', sans-serif;
}

.modal-body input {
  width: 90%;
  padding:10px;
  border: 1px solid #dadce0;
  border-radius: 8px;
  font-size: 16px;
  font-family: 'Roboto', sans-serif;
}

.modal-footer {
  display: flex;
  justify-content: space-around;
}

.modal-footer button {
  margin-left: 10px;
  padding: 10px 45px;
  font-size: 16px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-family: 'Roboto', sans-serif;
  margin-right: 0;
}


.modal-footer .cancel-button {
  background-color: #f5f5f5;
  color: #3c4043;
}

.modal-footer .cancel-button:hover {
  background-color: #ebebeb;
}

.modal-footer .confirm-button {
  background-color: #1a73e8;
  color: #fff;
}

.modal-footer .confirm-button:hover {
  background-color: #174ea6;
}
.payCom{
  margin-top: 80px;
}
.payCom button{
  background-color: #05e913;
  color: white;
  border: none;
  padding: 8px 70px;
  display: inline-block;
  padding: 7px 70px;
  margin: 10px;
  font-size: 16px;
  transition: background-color 0.3s ease;
  border-radius: 4px
}

  </style>
  